<?php

namespace Shahu\Common\model;

use Illuminate\Database\Eloquent\Model;
use Shahu\Common\enum\DeleteEnum;
use support\Db;

class BaseModel extends Model
{

    protected static string $primary_key = 'id';
    protected static string $table_name = '';
    protected static string $table_alias = '';
    protected static string $delete_field = 'is_delete';
    protected static array $field_arr = ['id'];
    /**
     * @var bool 是否自增
     */
    public $incrementing = true;
    /**
     * @var bool 是否维护创建时间和更新时间
     */
    public $timestamps = true;
    /**
     * @var string 主键
     */
    protected $primaryKey = 'id';

    /**
     * 查询字段转换
     * @param string $field
     * @return array|string[]
     */
    protected static function getFields(string $field = ''): array
    {
        //空字段返回默认
        if (empty($field)) {
            return static::$field_arr;
        } else {
            //数组直接返回
            if (is_array($field)) {
                return $field;
            } else {
                //字符串转数组
                return explode(',', $field);
            }
        }
    }

    /**
     * 根据ID查询单条记录
     * @param int $id
     * @param string $field
     * @return array
     */
    public static function selectOneById(int $id, string $field = ''): array
    {
        //处理结果
        return self::selectOneByKeyAndValue(self::$primary_key, $id, $field);
    }

    /**
     * 根据字段查询合集
     * @param string $key
     * @param $value
     * @param string $field
     * @return array
     */
    public static function selectOneByKeyAndValue(string $key, $value, string $field = ''): array
    {
        if (!empty($value) && !empty($key)) {
            $result = Db::table(static::$table_name)
                ->select(static::getFields($field))
                ->where($key, $value)
                ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
                ->limit(1)
                ->first();
            return static::handleSelectResult($result);
        }
        return [];
    }


    /**
     * 根据id集合查询菜单
     * @param array $id_arr
     * @param string $field
     * @return array
     */
    public static function selectByIdArr(array $id_arr = [], string $field = ''): array
    {
        return self::selectByKeyAndArr(self::$primary_key, $id_arr, $field);
    }


    /**
     * 根据字段查询合集
     * @param string $key
     * @param $value
     * @param string $field
     * @return array
     */
    public static function selectByKeyAndValue(string $key, $value, string $field = ''): array
    {
        if (!empty($value) && !empty($key)) {
            $result = Db::table(static::$table_name)
                ->select(static::getFields($field))
                ->where($key, $value)
                ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
                ->get();
            return static::handleSelectResult($result);
        }
        return [];
    }


    /**
     * 根据字段查询合集
     * @param string $key
     * @param array $arr
     * @param string $field
     * @return array
     */
    public static function selectByKeyAndArr(string $key, array $arr = [], string $field = ''): array
    {
        if (!empty($arr) && !empty($key)) {
            $result = Db::table(static::$table_name)
                ->select(static::getFields($field))
                ->whereIn($key, $arr)
                ->where(static::$delete_field, (DeleteEnum::LIVE)->value)
                ->get();
            return static::handleSelectResult($result);
        }
        return [];
    }

    /**
     * 插入
     * @param array $data
     * @return bool
     */
    public static function insert(array $data): bool
    {
        if (count($data) == count($data, 1)) {
            //没有设置create_user，用当前用户赋值
            if (!array_key_exists('create_user', $data)) {
                $data['create_user'] = $GLOBALS['user_name'] ?? '';
            }
        } else {
            foreach ($data as &$one) {
                //没有设置create_user，用当前用户赋值
                if (!array_key_exists('create_user', $one)) {
                    $one['create_user'] = $GLOBALS['user_name'] ?? '';
                }
            }
        }
        //插入
        return Db::table(static::$table_name)->insert($data);
    }

    /**
     * 插入数据，返回ID
     * @param array $data
     * @return bool|int
     */
    public static function insertGetId(array $data): bool|int
    {
        //没有设置create_user，用当前用户赋值
        if (!array_key_exists('create_user', $data)) {
            $data['create_user'] = $GLOBALS['user_name'] ?? '';
        }
        //插入
        $id = Db::table(static::$table_name)->insertGetId($data);
        return $id > 0 ? $id : false;
    }

    /**
     * 更新
     * @param $id
     * @param $data
     * @return bool
     */
    public static function updateData($id, $data): bool
    {
        //没有设置create_user，用当前用户赋值
        if (!array_key_exists('update_user', $data)) {
            $data['update_user'] = $GLOBALS['user_name'] ?? '';
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
        //插入
        return Db::table(static::$table_name)
            ->where(self::$primary_key, $id)
            ->where(self::$delete_field, (DeleteEnum::LIVE)->value)
            ->update($data);
    }


    /**
     * 更新
     * @param $id_arr
     * @param $data
     * @return bool
     */
    public static function updateDataByIdArr($id_arr, $data): bool
    {
        //没有设置create_user，用当前用户赋值
        if (!array_key_exists('update_user', $data)) {
            $data['update_user'] = $GLOBALS['user_name'] ?? '';
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
        //插入
        return Db::table(static::$table_name)
            ->whereIn(self::$primary_key, $id_arr)
            ->where(self::$delete_field, (DeleteEnum::LIVE)->value)
            ->update($data);
    }


    /**
     * 根据字段更新
     * @param $field
     * @param $value
     * @param $data
     * @return bool
     */
    public static function updateDataByField($field, $value, $data): bool
    {
        //没有设置create_user，用当前用户赋值
        if (!array_key_exists('update_user', $data)) {
            $data['update_user'] = $GLOBALS['user_name'];
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
        //插入
        return Db::table(static::$table_name)
            ->where($field, $value)
            ->where(self::$delete_field, (DeleteEnum::LIVE)->value)
            ->update($data);
    }


    /**
     * 更新
     * @param $field
     * @param $value_arr
     * @param $data
     * @return bool
     */
    public static function updateMultiDataByField($field, $value_arr, $data): bool
    {
        //没有设置create_user，用当前用户赋值
        if (!array_key_exists('update_user', $data)) {
            $data['update_user'] = $GLOBALS['user_name'] ?? '';
            $data['updated_at'] = date('Y-m-d H:i:s');
        }
        //插入
        return Db::table(static::$table_name)
            ->whereIn($field, $value_arr)
            ->where(self::$delete_field, (DeleteEnum::LIVE)->value)
            ->update($data);
    }


    /**
     * 根据field删除多条记录
     * @param $field
     * @param array $id_arr
     * @return bool
     */
    public static function deleteByIdArr($field, array $id_arr): bool
    {
        if (!empty($id_arr)) {
            $count = Db::table(static::$table_name)
                ->whereIn($field, $id_arr)
                ->where(self::$delete_field, (DeleteEnum::LIVE)->value)
                ->delete();
            if ($count > 0) {
                return true;
            }
        }
        return false;
    }


    /**
     * 处理查询结果
     * @param $result
     * @return array
     */
    public static function handleSelectResult($result): array
    {
        if (!empty($result)) {
            $data = json_decode(json_encode($result), true);
        }
        return $data ?? [];
    }
}
